package com.metaera.app.controller.presenter;

import com.metaera.app.controller.core.RequestPresenter;
import com.metaera.app.controller.view.core.INetworkRequestView;
import com.metaera.app.data.DataRepository;
import com.metaera.app.data.model.BasicResponse;
import com.metaera.app.data.rx.ResponseObserver;
import com.metaera.app.data.rx.SchedulersTransformer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.functions.Function;

public class CalendarPresenter extends RequestPresenter<INetworkRequestView<List<Date>>> {

    public void execute(String date, int categoryID) {
        DataRepository.getInstance()
                .calendarList(date, categoryID)
                .map((Function<BasicResponse<List<String>>, BasicResponse<List<Date>>>) response -> {
                    List<String> list = response.getData();
                    if (list == null || list.isEmpty()) {
                        return new BasicResponse<>(new ArrayList<>(), response.getCode(), response.getMessage());
                    }

                    List<Date> dateList = new ArrayList<>();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

                    for (String s : list) {
                        dateList.add(simpleDateFormat.parse(s));
                    }

                    return new BasicResponse<>(dateList, response.getCode(), response.getMessage());
                })
                .compose(SchedulersTransformer.transformer())
                .subscribe(new ResponseObserver<>(
                                this,
                                mView,
                                response -> mView.successful(response.getData())
                        )
                );
    }

}
